import datetime
import os, time
from untitled import settings
import threading
from pprint import pprint
from .Html_structure import Template_mixin

dict_devices = {}
devices_z = {}
time_start = ''


def dog(applist, appname, activityname):
    app_dz = os.path.join(settings.app_z) + appname + '.apk'
    path_log = os.path.join(settings.app_log)
    t_list = []
    for value in applist:
        os.popen('adb -s ' + str(applist[value]) + ' logcat -c')
        devices_z.setdefault(value)
        devices_z[value] = {}
        devices_z[value]['key'] = str(applist[value]) + "_" + str(int(time.time()))
        t = threading.Thread(target=apptest, args=(str(applist[value]), appname, value, app_dz, activityname, path_log))
        t.setDaemon(True)  # 开启守护进程
        t.start()
        t_list.append(t)
        for t in t_list:
            t.join()  # 主线程等待子线程结束


def apptest(devices, appname, value, app_dz, activityname, path_log):
    WaitTime_list_cold = []
    WaitTime_list_heat = []
    screenshot_list = []
    screenshot_time = []
    video_name_list = []
    cpu_time = []
    cpu_percentage = []
    time_video_name = str(int(time.time())) + devices
    video_name_list.append(time_video_name)
    run_video(devices, time_video_name)

    os.popen("adb -s " + devices + " install " + app_dz)
    print(os.popen("adb -s " + devices + " install " + app_dz), 1111111111111)
    time_start = datetime.datetime.now()  # 开始时间

    time.sleep(15)
    apk = os.popen('adb -s ' + devices + ' shell pm list packages | findstr "%s"' % appname)
    print(os.popen('adb -s ' + devices + ' shell pm list packages | findstr "%s"' % appname), 222222222)
    a = [i for i in apk]
    if a != []:
        devices_z[value]['install'] = "True"
    else:
        devices_z[value]['install'] = "False"
    time.sleep(15)
    content = os.popen("adb -s " + devices + " shell am start -W -n " + appname + "/" + activityname)
    print(os.popen("adb -s " + devices + " shell am start -W -n " + appname + "/" + activityname), 333333333333)
    time.sleep(1)
    for line in content.readlines():
        WaitTime_list_cold.append(line.replace('\n', ''))
    temperature = int(WaitTime_list_cold[-2].replace('WaitTime: ', '')) / 1000
    devices_z[value]['time_c'] = str('%.2f' % temperature)
    time.sleep(1)
    for i in devices_z:
        devices_z[i]['cpu'] = {}

        cpu_t, cpu_p = app_cpu(devices, appname)
        cpu_time.append(cpu_t)
        cpu_percentage.append(cpu_p)
        devices_z[i]['cpu'][cpu_t] = cpu_p

        time.sleep(1)
        cpu_t, cpu_p = app_cpu(devices, appname)
        cpu_time.append(cpu_t)
        cpu_percentage.append(cpu_p)
        devices_z[i]['cpu'][cpu_t] = cpu_p

        time.sleep(1)
        cpu_t, cpu_p = app_cpu(devices, appname)
        cpu_time.append(cpu_t)
        cpu_percentage.append(cpu_p)
        time.sleep(1)
        time_cpu = datetime.datetime.now().strftime('%H_%M_%S')
        devices_z[i]['cpu'][cpu_t] = cpu_p

    os.popen("adb -s " + devices + " shell am force-stop " + appname)
    print("adb -s " + devices + " shell am force-stop " + appname, 4444444444444444)

    content = os.popen("adb -s " + devices + " shell am start -W -n " + appname + "/" + activityname)
    for line in content.readlines():
        WaitTime_list_heat.append(line.replace('\n', ''))
    temperature = int(WaitTime_list_heat[-2].replace('WaitTime: ', '')) / 1000
    devices_z[value]['time_h'] = str('%.2f' % temperature)

    time.sleep(10)

    run_logname(devices, path_log, appname)

    os.popen("adb -s " + devices + " uninstall %s" % appname)
    apk = os.popen('adb -s ' + devices + ' shell pm list packages | findstr "%s"' % appname)
    a = [i for i in apk]
    if a != []:
        devices_z[value]['uninstall'] = "False"
    else:
        devices_z[value]['uninstall'] = "True"
    for i in devices_z:
        devices_z[i]['screencaps'] = {}
        time_jt, pngname_jt = run_time_screenshot(devices)
        devices_z[i]['screencaps'][time_jt] = settings.app_png + pngname_jt + '.png'

        screenshot_list.append(pngname_jt)
        screenshot_time.append(time_jt)
        time.sleep(2)
        time_jt, pngname_jt = run_time_screenshot(devices)
        devices_z[i]['screencaps'][time_jt] = settings.app_png + pngname_jt + '.png'

        screenshot_list.append(pngname_jt)
        screenshot_time.append(time_jt)
        time.sleep(2)
        time_jt, pngname_jt = run_time_screenshot(devices)
        devices_z[i]['screencaps'][time_jt] = settings.app_png + pngname_jt + '.png'

        screenshot_list.append(pngname_jt)
        screenshot_time.append(time_jt)
    # 导出截图
    print('screenshot_list', screenshot_list)
    run_pull(devices, screenshot_list)

    # 导出视频
    app_video = os.path.join(settings.app_video)
    run_process(devices, time_video_name, app_video)
    push(devices)

    time_termination = datetime.datetime.now()
    time_calculation = str(time_termination - time_start)
    time.sleep(1)
    for i in devices_z:
        devices_z[i]['Test_time'] = str(time_calculation.split('.')[0])
        devices_z[i]['Data_time'] = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')


def getDevicesAll():
    devices = []
    try:
        for dName_ in os.popen("adb devices"):
            if "\t" in dName_:
                if dName_.find("emulator") < 0:
                    devices.append(dName_.split("\t")[0])
        devices.sort(cmp=None, key=None, reverse=False)
    except:
        pass

    # print(u"\n设备号: %s \n总数量:%s台" % (devices, len(devices)))
    """
        {0:{"厂商名称":"","设备型号":"","安卓版本":"","分辨率":"","设备码":""},1:{"厂商名称":"","设备型号":"","安卓版本":"","分辨率":"","设备码":""}}
    """
    for index, i in enumerate(devices):
        # dict_devices.setdefault(str(index))
        dict_devices[str(index)] = {}
        dict_devices[str(index)]['key'] = i + "_" + str(int(time.time()))
        # 厂商名称
        dict_devices[str(index)]['Mobile_phone_brands'] = os.popen(
            ' adb -s ' + i + ' shell getprop ro.product.brand').read().replace('\n', '')
        # 设备型号
        dict_devices[str(index)]['phone_brands_version'] = os.popen(
            ' adb -s ' + i + ' shell getprop ro.product.model').read().replace(
            '\n', '')
        # 安卓版本
        dict_devices[str(index)]['Android_version'] = os.popen(
            ' adb -s ' + i + ' shell getprop ro.build.version.release').read().replace('\n',
                                                                                       '')
        # 分辨率
        dict_devices[str(index)]['phone_px'] = os.popen(' adb -s ' + i + ' shell wm size').read().replace(
            'Physical size: ',
            '').replace(
            '\n', '')
        # 设备码
        dict_devices[str(index)]['phone_code'] = i

    return dict_devices


def run_time_screenshot(devices):
    pngname = str(int(time.time())) + devices
    pngtime = datetime.datetime.now().strftime('%H:%M:%S')
    os.popen('adb -s ' + devices + f' shell screencap -p /sdcard/{pngname}.png')

    return str(pngtime), pngname


def run_video(devices, time_video_name):
    print("adb -s " + devices + f" shell screenrecord /sdcard/{time_video_name}.mp4")
    try:
        os.popen("adb -s " + devices + f" shell screenrecord /sdcard/{time_video_name}.mp4")  # 开始录制视频 180s
    except:
        pass


def run_logname(devices, path_log, appname):
    bugtime = int(time.time())
    uid = os.popen('adb -s ' + devices + ' shell ps |findstr "%s"' % appname)
    print('adb -s ' + devices + ' shell ps |findstr "%s"' % appname)
    uid_list = []
    uid_ayl = [i for i in uid]
    print('uid', uid)
    print('uid_ayl', uid_ayl)
    if uid_ayl != []:
        for j in uid_ayl[0].split(' '):
            if j != '':
                uid_list.append(j)
        print(uid_list[1], path_log)
        os.popen(
            'adb -s ' + devices + f' shell "logcat *:W | findstr {uid_list[1]}" > {path_log}{bugtime}{"_" + devices}.txt')
        print(
            'adb -s ' + devices + f' shell "logcat *:W | findstr {uid_list[1]}" > {path_log}{bugtime}{"_" + devices}.txt',
            55555555555)
    else:
        pass


def run_process(devices, time_video_name, app_video):
    try:
        os.popen('adb -s ' + devices + ' shell "ps -A | findstr screenrecord"')
        time.sleep(1)
        os.popen("adb -s " + devices + " pull /sdcard/%s.mp4 %s" % (time_video_name, app_video))
    except:
        pass


def app_cpu(devices, appname):
    cpu_list = []
    adb_cpu = os.popen("adb -s " + devices + " shell top -n 1 ")
    print("adb -s " + devices + " shell top -n 1 ", 111111111111111112222222222222222333333333)
    app_name = appname.split('.')[0:-1][0] + "." + appname.split('.')[0:-1][1]
    for i in adb_cpu:
        if app_name in i.replace('\n', ''):
            cpu_number = i.replace('\n', '').split(' ')
            cpu_list = list(filter(None, cpu_number))
    return datetime.datetime.now().strftime('%H:%M:%S'), cpu_list[-4]


def run_pull(devices, pngnamelist):
    for name in pngnamelist:
        time.sleep(1)
        os.popen('adb -s ' + devices + f' pull /sdcard/{name}.png {settings.app_png}')
        print('adb -s ' + devices + f' pull /sdcard/{name}.png {settings.app_png}')


def push(devices):
    dict_devices_1 = dict(devices_z['0'], **dict_devices['0'])
    dict_len = {}
    for i in range(len(dict_devices_1)):
        dict_len[str(i)] = dict_devices_1
    print(dict_len)
    while True:
        pprint(dict_len)
        """
        # :return
        # numfail + numsucc + table_td(dict)中参数值需根据实际运行结果赋值
        # """
        table_tr0 = ''
        instafail = 0
        instasucc = 0
        uninstafail = 0
        uninstasucc = 0
        html = Template_mixin()
        for i in dict_len:
            if dict_len[i]['install'] == 'True':
                instasucc += 1
            else:
                instafail += 1
            if dict_len[i]['uninstall'] == 'True':
                uninstasucc += 1
            else:
                uninstafail += 1

            table_td = html.TABLE_TMPL % dict(implement_def=i,
                                              version=dict_len[i]['key'],
                                              install=dict_len[i]['install'],
                                              cold=dict_len[i]['time_c'],
                                              hot=dict_len[i]['time_h'],
                                              cpu=dict_len[i]['cpu'],
                                              uninstall=dict_len[i]['uninstall'],
                                              screencaps=dict_len[i]['screencaps'],
                                              Mobile_phone_brands=dict_len[i]['Mobile_phone_brands'],
                                              phone_brands_version=dict_len[i]['phone_brands_version'],
                                              Android_version=dict_len[i]['Android_version'],
                                              phone_px=dict_len[i]['phone_px'],
                                              phone_code=dict_len[i]['phone_code'],
                                              )
            table_tr0 += table_td  # 列表中行数据

        total_str = '安装通过 %s，失败 %s， 卸载通过 %s，失败 %s' % (instasucc, instafail, uninstasucc, uninstafail)  # 测试结果

        # 传参 向Html_structure.py进行传递参数
        output = html.HTML_TMPL % dict(value=total_str, table_tr=table_tr0, )

        filename = '{date}_TestReport.html'.format(date=time.strftime('%Y%m%d%H%M%S'))  # 生成html报告
        dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), './html')  # 获取interface的路径
        filename = os.path.join(dir, filename)
        with open(filename, 'wb') as f:
            f.write(output.encode('utf8'))

        break
